import io from 'socket.io-client';

let socket = '';

export const sk = socket

export const emit = (action) => {
  socket.emit(action.type, action.data);
};

export const listen = (action) => {
  if (socket === '') socket = io('localhost:3008');

  socket.on('connect', () => {
    action({
      type: 'connect',
      state: 'ok',
      msg: '已连接服务器！',
    });
  });

  socket.on('disconnect', () => {
    action({
      type: 'msg',
      state: 'war',
      msg: '与接服务器链接已断开！',
    });
  });

  socket.on('msg', (data) => {
    action({
      type: data.type,
      msg: data.msg,
    });
  });

  socket.on('ok', (msg) => {
    action({
      type: 'ok',
      msg: msg,
    });
  });

  socket.on('loading', (loading) => {
    console.log(loading);
    action({
      type: 'loading',
      data: loading,
    });
  });

  socket.on('profile_list', (list) => {
    action({
      type: 'profile_list',
      data: list,
    });
  });

  socket.on('profile', (profile) => {
    action({
      type: 'profile',
      data: profile,
    });
  });

  socket.on('user', (user) => {
    action({
      type: 'login',
      data: user,
    });
  });

  socket.on('user_list', (data) => {
    action({
      type: 'user_list',
      data: data,
    });
  });
};
